package blackhouse.thread;

class Q
{
	private String name = "unknow";
	private String sex = "unknow";
	boolean befull = false;

	public synchronized void put(String name, String sex)
	{
		if (befull)
			try
			{
				wait();
			} catch (InterruptedException e1)
			{
				e1.printStackTrace();
			}
		this.name = name;
		try
		{
			Thread.sleep(1);
		} catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		this.sex = sex;
		befull = true;
		notify();
	}

	public synchronized void get()
	{
		if (!befull)
			try
			{
				wait();
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		System.out.print(name);
		System.out.println(":" + sex);
		befull = false;
		notify();
	}
}

class Producer implements Runnable
{
	Q q;

	public Producer(Q q)
	{
		this.q = q;
	}

	public void run()
	{
		int i = 0;
		while (true)
		{
			// synchronized (q)
			// {
			// if (q.befull)
			// try
			// {
			// wait();
			// } catch (InterruptedException e1)
			// {
			// e1.printStackTrace();
			// }
			// if (i == 0)
			// {
			// q.name = "zhangsan";
			// try
			// {
			// Thread.sleep(1);
			// } catch (InterruptedException e)
			// {
			// e.printStackTrace();
			// }
			// q.sex = "male";
			// } else
			// {
			// q.name = "lisi";
			// q.sex = "famale";
			// }
			// q.befull = true;
			// q.notify();
			// }
			if (i == 0)
			{
				q.put("zhangsan", "male");
			} else
			{
				q.put("lisi", "famale");
			}
			i = (i + 1) % 2;
		}
	}

}

class Consumer implements Runnable
{
	Q q;

	public Consumer(Q q)
	{
		this.q = q;
	}

	public void run()
	{
		while (true)
		{
			// synchronized (q)
			// {
			// if (!q.befull)
			// try
			// {
			// q.wait();
			// } catch (InterruptedException e)
			// {
			// e.printStackTrace();
			// }
			// System.out.print(q.name);
			// System.out.println(q.sex);
			// q.befull = false;
			// q.notify();
			q.get();
		}
	}
}

public class ThreadCommunation
{
	public static void main(String[] args)
	{
		// Q q = new Q();
		// new Thread(new Producer(q)).start();
		// new Thread(new Consumer(q)).start();
		ThreadTest tt = new ThreadTest();
		new Thread(tt).start();
		for (int i = 0; i < 100; i++)
		{
			if (i == 50)
				tt.stopMe();
			System.out.println("main() is running!");
		}
	}
}

class ThreadTest implements Runnable
{
	private boolean bstop = false;

	public boolean stopMe()
	{
		return bstop = true;
	}

	public void run()
	{
		while (!bstop)
			System.out.println(Thread.currentThread().getName()
					+ " is running");
	}

}
